package com.yjd.comm.util;

import java.net.URLEncoder;
import java.security.Key;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class CryptAES {

	private static final String AESTYPE = "AES/ECB/PKCS5Padding";

	public static String AES_Encrypt(String keyStr, String plainText) {
		byte[] encrypt = null;
		try {
			Key key = generateKey(keyStr);
			Cipher cipher = Cipher.getInstance(AESTYPE);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			encrypt = cipher.doFinal(plainText.getBytes("UTF-8"));
			return new String(Base64.encodeBase64(encrypt),"UTF-8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String AES_Decrypt(String keyStr, String encryptData) {
		byte[] decrypt = null;
		try {
			Key key = generateKey(keyStr);
			Cipher cipher = Cipher.getInstance(AESTYPE);
			cipher.init(Cipher.DECRYPT_MODE, key);
			decrypt = cipher.doFinal(Base64.decodeBase64(encryptData.getBytes("UTF-8")));
			return new String(decrypt,"UTF-8").trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static Key generateKey(String key) throws Exception {
		try {
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
			return keySpec;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

	public static void main(String[] args) throws Exception {

		String keyStr = SecurityCode.md5("njntIgTthFHTB9PAaq9NN54vAS5e");
		Map<String,Object> map = FrameUtil.newLinkedHashMap("mobile","15800926537","content","您的验证码是123456","sendtime","-1");
		System.out.println(FrameUtil.json(map));
		String plainText = FrameUtil.json(map);

		String encText = AES_Encrypt(keyStr, plainText);
		String decString = AES_Decrypt(keyStr, encText);
		System.out.println("秘钥：" + keyStr);
		System.out.println("明文：" + plainText);
		System.out.println("密文：" + encText);
		System.out.println(URLEncoder.encode(encText,"utf-8"));
		System.out.println("解密：" + decString);

	}
}